const express = require('express')
const app = express() 
const cors = require('cors')
const api = require('./modules/api/index.js')
const bodyParser = require('body-parser')
//解决跨域问题，前端项目打包完成后可去除跨域
app.use(cors())
app.use(express.json())

//模板引擎
const path = require('path')
const ejs = require('ejs')
app.engine('html', ejs.renderFile)
app.set('view engine', 'html')
app.use('/', express.static(path.join(__dirname, './views')))

app.use(bodyParser.urlencoded({ extended: false }))
app.use('/', api)

app.all('*', function (request, response) {
  response.sendFile(path.resolve(__dirname, 'views', 'index.html'))
})
//获取内网IP
function getIPAddress() {
  var interfaces = require('os').networkInterfaces();
  for (var devName in interfaces) {
    var iface = interfaces[devName];
    for (var i = 0; i < iface.length; i++) {
      var alias = iface[i];
      if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
        return alias.address;
      }
    }
  }
}
//获取公网IP
const publicIp = require('public-ip')
async function getPublicIP() {
  return publicIp.v4()
}
app.listen(301,'0.0.0.0', () => {
  console.log("\x1b[31m", '内网请访问')
  console.log("\x1b[34m", 'http://' + getIPAddress() + ':301')
  console.log("\x1b[31m", '外网请访问');
  (async function () {
    console.log("\x1b[34m",'http://' + await getPublicIP()+ ':301')
    console.log("\x1b[31m", '无网请访问');
    console.log("\x1b[34m", 'http://localhost:301')
    console.log("\x1b[37m")
  })()

})